package org.yly.game.rpggame.domain.model.task.condition;

import java.util.Map;

import org.yly.game.rpggame.domain.model.DomainEventPublisher;
import org.yly.game.rpggame.domain.model.DomainEventSubscriber;
import org.yly.game.rpggame.domain.model.monster.MonsterDeadEvent;
import org.yly.game.rpggame.domain.model.task.AcceptedTask;

/**
 * 杀怪任务需要
 * 
 * @author makefu
 * 
 */
public class KillMonsterCompleteCondition implements TaskCompleteCondition {

	private Map<String, Integer> deadMonsterIdMap; // 已经死亡怪物ID

	private boolean isOk = false;

	public KillMonsterCompleteCondition(final AcceptedTask task, final Map<String, Integer> needKillMonsterIdMap) {
		// 订阅怪物死亡事件
		DomainEventPublisher.getInstance().subscribe(new DomainEventSubscriber<MonsterDeadEvent>() {

			@Override
			public void handleEvent(MonsterDeadEvent domainEvent) {
				if (needKillMonsterIdMap.containsKey(domainEvent.getMonsterId())) {
					if (deadMonsterIdMap.containsKey(domainEvent.getMonsterId())) {
						deadMonsterIdMap.put(domainEvent.getMonsterId(),
								deadMonsterIdMap.get(domainEvent.getMonsterId()) + 1);
					} else {
						deadMonsterIdMap.put(domainEvent.getMonsterId(), 1);
					}
					for (String mosterId : needKillMonsterIdMap.keySet()) {
						Integer deadCount = needKillMonsterIdMap.get(mosterId);
						deadCount = deadCount == null ? 0 : deadCount;
						Integer needCount = deadMonsterIdMap.get(mosterId);
						needCount = needCount == null ? 0 : needCount;
						if (deadCount >= needCount) {
							isOk = true;
							task.checkCompleteCondition();
						}
					}
				}
			}

			@Override
			public Class<MonsterDeadEvent> subscribedToEventType() {
				return MonsterDeadEvent.class;
			}
		});
	}

	@Override
	public boolean check() {
		return isOk;
	}

	public Map<String, Integer> getDeadMonsterIdMap() {
		return deadMonsterIdMap;
	}

	public boolean isOk() {
		return isOk;
	}

}
